package com.example.shiyansan.config;

import com.example.shiyansan.interceptor.JwtTokenInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                // 启用CORS并禁用CSRF（Spring Security 6.x+新写法）
                .cors(cors -> cors.configure(http)) // 修正1：正确启用CORS
                .csrf(csrf -> csrf.disable()) // 修正2：新式写法禁用CSRF

                // 配置请求授权
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() // 放行所有OPTIONS请求
                        .requestMatchers("/user/user/login", "/user/user/register").permitAll() // 放行登录注册接口
                        .requestMatchers("/user/book/**").permitAll()
                        .requestMatchers("/user/cart/**").permitAll()
                        .requestMatchers("/user/order/**").permitAll()
                        .requestMatchers("/admin/common/**").permitAll()
                        .requestMatchers("/user/export/**").permitAll()
                        .anyRequest().authenticated()
                );

        return http.build();
    }
}